package com.eagle.videoboot.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MergeVideoMp3 {

	public void convert(String videoInputPath, String mp3InputPath,
						double seconds, String videoOutputPath) throws Exception{
		String arrayFilenameItem[] =  videoInputPath.split("\\.");
		String extractVideo = arrayFilenameItem[0]+".avi";

//		System.out.println(videoInputPath);
//		System.out.println(extractVideo);

		this.extractVideo(videoInputPath, extractVideo);
		System.out.println("=============extractVideo done");
		this.merge(extractVideo,mp3InputPath,13,videoOutputPath);
		System.out.println("=============merge done");

		File file = new File(extractVideo);
		if (file.exists() && file.isFile()){
			file.delete();
		}

	}

	public void extractVideo(String videoInputPath, String videoOutputPath) throws Exception {
		//抽取
		//ffmpeg -i 3.mp4 -an -codec copy 3.avi

		List<String> command = new ArrayList<>();
		command.add("ffmpeg");
		command.add("-i");
		command.add(videoInputPath);
		command.add("-an");
		command.add("-codec");
		command.add("copy");
		command.add(videoOutputPath);
		execute(command);

	}

	private void execute(List<String> command) throws IOException {
		ProcessBuilder builder = new ProcessBuilder(command);
		Process process = builder.start();

		InputStream errorStream = process.getErrorStream();
		InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
		BufferedReader br = new BufferedReader(inputStreamReader);

		String line = "";
		while ((line = br.readLine()) != null) {
		}

		if (br != null) {
			br.close();
		}
		if (inputStreamReader != null) {
			inputStreamReader.close();
		}
		if (errorStream != null) {
			errorStream.close();
		}
	}


	public void merge(String videoInputPath, String mp3InputPath,
					  double seconds, String videoOutputPath) throws Exception {

		//合并
		//ffmpeg -i 3.avi -i music2.mp3 -t 13 -y result.mp4
		List<String> command = new ArrayList<>();
		command.add("ffmpeg");
		command.add("-i");
		command.add(videoInputPath);
		command.add("-i");
		command.add(mp3InputPath);
		command.add("-t");
		command.add(String.valueOf(seconds));
		command.add("-y");
		command.add(videoOutputPath);

		execute(command);

	}

	public static void main(String[] args) {
		MergeVideoMp3 ffmpeg = new MergeVideoMp3();
		String source = "F:\\video-upload\\视频素材\\test\\14.mp4";
		String mp3 = "F:\\video-upload\\视频素材\\test\\1.mp3";
		String target = "F:\\video-upload\\视频素材\\test\\result.mp4";
		try {
			ffmpeg.convert(source,mp3,12,target);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
